package com.wehealth.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class DoTask extends AsyncTask<String, String, String> {
	
	private Handler handler;
	//private Context context;
	
	public DoTask(Context c,Handler h){
		//this.context = c;
		this.handler = h;
	}
	
	@Override
	protected String doInBackground(String... uri) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpResponse response;
		String responseString = null;
		try {
			response = httpclient.execute(new HttpGet(uri[0]));
			StatusLine statusLine = response.getStatusLine();
			if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				response.getEntity().writeTo(out);
				out.close();
				responseString = out.toString();
			} else {
				responseString="1";
				response.getEntity().getContent().close();
			}
		} catch (ClientProtocolException e) {
			responseString="1";
			e.printStackTrace();
		} catch (IOException e) {
			responseString="1";
			e.printStackTrace();
		}catch(Exception e){
			responseString="1";
			e.printStackTrace();
		}
		return responseString;
	}
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}
	@Override
	protected void onPostExecute(String response) {
		super.onPostExecute(response);
		Bundle bundle = new Bundle();
	    bundle.putString("msg", response);
	    Message message = new Message();
	    message.setData(bundle);
		handler.sendMessage(message);
	}
}
